package com.jyw.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jyw.R;
import com.jyw.network.OkHttpManager;
import com.jyw.network.Server;
import com.jyw.pojo.EventBusTypes;

import java.io.IOException;
import java.util.regex.Pattern;

import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author simonw
 * @version 1.0
 * @created 2017/1/8
 */

public class RecommondMineActivity extends BaseActivity implements View.OnClickListener {
    private EditText editMobile;
    private TextView btnGo;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_recommond_mine);

        editMobile = (EditText) findViewById(R.id.edit_mobile);
        btnGo = (TextView) findViewById(R.id.btn_go);

        findViewById(R.id.iv_back).setOnClickListener(this);
        btnGo.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_go:
                if (!isValidate()) {
                    break;
                } else {
                    go();
                }
                break;
            case R.id.iv_back:
                onBackPressed();
                break;
        }
    }

    private void go() {
        Request request = new Request.Builder().
                url(Server.ADD_RECOMMENDED + "?mobile=" + editMobile.getText().toString()
                ).build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(RecommondMineActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                OkHttpManager.backgroundThreadShortToast(RecommondMineActivity.this, "" + response.body().string());
                finish();
            }
        });
    }

    private boolean isValidate() {
        if (editMobile.getText().toString().equals("")) {
            Toast.makeText(RecommondMineActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        Pattern p1 = Pattern.compile("^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$");
        if (!p1.matcher(editMobile.getText().toString()).matches()) {
            Toast.makeText(RecommondMineActivity.this, "手机号有误", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }
}
